﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ExamDemo.Data;
using ExamDemo.Models;
using ExamDemo.ParamModel;
using Newtonsoft.Json;

namespace ExamDemo.Controllers
{
    public class UsersController : Controller
    {
        private UsersContext db = new UsersContext();

        // GET: Users
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        // GET: Users/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // GET: Users/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Users/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Username,Password,CreatedAt,UpdatedAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(users);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Username,Password,CreatedAt,UpdatedAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Entry(users).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(users);
        }

        // GET: Users/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Users users = db.Users.Find(id);
            db.Users.Remove(users);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        public ActionResult Login(LoginModel login)
        {
            return View();
        }

        public ActionResult Register() {
            return View();
        }

        public string LoginDone(LoginModel login)
        {
            dynamic res;

            if (login.Username.Trim().Length > 0 && login.Password.Trim().Length > 0)
            {
                var username = login.Username.Trim();
                var password = login.Password.Trim();
                var userList = db.Users.ToList();

                var user = db.Users.Where(x => x.Username.Equals(username) && x.Password.Equals(password)).FirstOrDefault();

                if (user != null)
                {
                    Session["Username"] = username;
                    var sessionId = userList.SingleOrDefault(x => x.Username == Session["Username"].ToString()).Id;
                    res = new
                    {
                        code = 200,
                        msg = "登录成功"
                    };
                }
                else
                {
                    res = new
                    {
                        code = 1000,
                        msg = "用户名或密码不正确"
                    };
                }
            }
            else
            {
                res = new
                {
                    code = 1000,
                    msg = "用户名密码不能为空"
                };
            }
            return JsonConvert.SerializeObject(res);
        }

        public string registerDone(RegisterModel registerModel)
        {
            var username = registerModel.Username.Trim();
            var password = registerModel.Password.Trim();
            var confirmPassword = registerModel.ConfirmPassword.Trim();

            dynamic res;

            if (username.Length > 0 && password.Length > 0 && password.Equals(confirmPassword))
            {
                var user = db.Users.Where(x => x.Username.Equals(username)).FirstOrDefault();

                if (user != null)
                {
                    res = new
                    {
                        code = 1000,
                        msg = "当前用户已注册"
                    };
                }
                else
                {
                    db.Users.Add(new Users
                    {
                        Username = username,
                        Password = password,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                        Version = 0
                    });

                    db.SaveChanges();

                    res = new
                    {
                        code = 200,
                        msg = "注册成功"
                    };
                }
            }
            else
            {
                res = new
                {
                    code = 1000,
                    msg = "用户名密码不能为空且两次密码应该一致"
                };
            }

            return JsonConvert.SerializeObject(res);
        }
    }
}
